/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.yaba.dbs.client;

import br.com.yaba.dbs.core.FileBackupException;
import br.com.yaba.dbs.core.Client;
import br.com.yaba.dbs.core.YabaData;
import br.com.yaba.dbs.core.Message;
import br.com.yaba.dbs.core.Chunk;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 *
 * @author emanuellfaustino
 */
public class ClientImpl implements Client {

    public String put(String userId, String filePath) throws FileBackupException {
        Socket socketClient = null;
        
        try {
        	
            socketClient = new Socket("localhost", 7777);
        
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        YabaData dataToBackup = new YabaData(userId, new File(filePath));
        
        Message ack = null;
        try {
        
            ObjectOutputStream output = new ObjectOutputStream(socketClient.getOutputStream());
            
            List<Chunk> allChunks = dataToBackup.getChunks(100);
            for(Chunk c : allChunks) {
                output.writeObject(c);
            }
        
            ObjectInputStream input = new ObjectInputStream(socketClient.getInputStream());
            
            ack = (Message)input.readObject();
            if (ack.isSuccess()) {
                return ack.getMessage();
            }
        
            socketClient.close();
        
        } catch(Exception ex) {
        	ex.printStackTrace();
        }
        
        return ack.getMessage();
    }

    public File get(String userId, String fileId, String filePath) throws FileBackupException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Map<String, String> getBackupedIds(String userId) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    

}
